package com.bluewap.api;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bluewap.api.object.Transaction;
import com.bluewap.core.Database;
import com.bluewap.core.StaticVar;
import com.bluewap.core.Util;

public class VerifyServlet extends HttpServlet {
	private static final long serialVersionUID = -1616617549984898217L;
	private Logger log = Logger.getLogger("verify");
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String transId = req.getParameter("id");
		String token = req.getParameter("token");
		String cpId = req.getParameter("cpid");

		if(!Util.isValidParam(transId)
				|| !Util.isValidParam(token)
				|| !Util.isValidParam(cpId)){
			log.info(StaticVar.ERROR_PARAM_MISSING + "|" + req.getQueryString());
			Util.printJson(StaticVar.ERROR_PARAM_MISSING, null, resp);
			return;
		}

		Connection conn = Database.getConnection();
		PreparedStatement st = null;
		ResultSet rs = null;
		boolean isExist = false;
		Transaction t = null;
		try {
			

			String query = "SELECT * FROM CHECKOUTS WHERE ID = ? AND TOKEN = ?  AND CP_ID = ?" ;
			st = conn.prepareStatement(query);
			st.setInt(1, Integer.valueOf(transId));
			st.setString(2, token);
			st.setInt(3, Integer.valueOf(cpId));
			rs = st.executeQuery();
			
			while (rs.next()){
				isExist = true;
				t = new Transaction();
				t.setId(rs.getInt(StaticVar.DB_CHECKOUT_ID));
				t.setToken(rs.getString(StaticVar.DB_CHECKOUT_TOKEN));
				t.setContentid(rs.getString(StaticVar.DB_CHECKOUT_CONTENTID));
				t.setContenttype(rs.getString(StaticVar.DB_CHECKOUT_CONTENTTYPE));
				t.setContentname(rs.getString(StaticVar.DB_CHECKOUT_CONTENTNAME));
				t.setContentprice(rs.getInt(StaticVar.DB_CHECKOUT_CONTENTPRICE));
				t.setStatus(rs.getInt(StaticVar.DB_CHECKOUT_STATUS));
				t.setReturnurl(rs.getString(StaticVar.DB_CHECKOUT_RETURNURL));
				break;
			}
		} catch (Exception e) {
			log.error("Error", e);
			Util.printJson(StaticVar.ERROR_INTERNAL_ERROR, null, resp);
			
			return;
			
		} finally{
			try {
				if (rs != null) rs.close();
				if (st != null) st.close();
				if (conn != null) Database.closeConnection(conn);
			} catch (Exception e) {
				log.error("Error", e);
			}
		}
		if(!isExist) {
			log.info(StaticVar.ERROR_TRANSACTION_NOT_EXIST + "|" + req.getQueryString());
			Util.printJson(StaticVar.ERROR_TRANSACTION_NOT_EXIST, null, resp);
			return;
		}
		else{
			log.info(t.getStatus() + "|" + req.getQueryString());
			Util.printJson(t.getStatus(), t, resp);
			return;
		}
	}
}
